<template>
	<div
		class="relative w-[90vw] md:w-[60vw] lg:w-[800px h-full max-h-[80vh] rounded-lg flex flex-col p-4 md:p-4 bg-white  dark:bg-black"
	>
		<button
			@click="emit('close')"
			class="absolute top-1 right-1 md:top-3 md:right-3 p-1 bg-gray-100 dark:bg-gray-800 rounded-full text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
		>
			<XIcon class="h-4 w-4" />
		</button>
		<!-- 搜索框 -->
		<div class="relative w-full max-w-2xl mx-auto mt-3">
			<SearchInput
				v-model="searchQuery"
				placeholder="请输入搜索内容"
				wrapper-class="relative w-full max-w-2xl mx-auto mt-3"
				@search="handleSearch"
			/>
		</div>

		<!-- 内容区域 -->
		<div class="flex-grow mt-4 w-full max-w-2xl mx-auto overflow-y-auto">
			<!-- 搜索历史 -->
			<div v-if="showHistorySection" class="animate-fade-in">
				<div class="flex justify-between items-center mb-2 px-2">
					<h2
						class="text-sm font-semibold text-gray-600 dark:text-gray-400"
					>
						搜索记录
					</h2>
					<div class="flex items-center space-x-3">
						<button
							@click="isEditingHistory = !isEditingHistory"
							class="text-xs text-gray-500 hover:text-sky-500"
						>
							{{ isEditingHistory ? "完成" : "编辑" }}
						</button>
						<button
							@click="searchStore.clearHistory()"
							class="text-xs text-gray-500 hover:text-red-500"
						>
							清空
						</button>
					</div>
				</div>
				<div class="flex flex-wrap gap-2 px-2">
					<div
						v-for="(item, index) in searchStore.history"
						:key="index"
						class="relative flex items-center bg-gray-100 dark:bg-gray-700 rounded-full py-1 pl-3 pr-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
						@click="handleHistoryClick(item)"
					>
						<div></div>
						<span>{{ item }}</span>
						<button
							v-if="isEditingHistory"
							@click.stop="searchStore.deleteHistoryItem(index)"
							class="absolute top-1 -right-1 -translate-y-1/2 ml-1.5 p-0.5 rounded-full bg-gray-100 hover:bg-gray-300 dark:hover:bg-gray-500"
						>
							<XIcon class="h-3 w-3" />
						</button>
					</div>
				</div>
			</div>

			<!-- 搜索结果 -->
			<div v-else-if="showResultsSection">
				<!-- 加载中 -->
				<div
					v-if="searchStore.isLoading"
					class="flex justify-center items-center pt-16"
				>
					<SpinnerIcon class="h-8 w-8 animate-spin text-sky-500" />
				</div>

				<!-- 错误提示 -->
				<div
					v-else-if="searchStore.error"
					class="text-center pt-16 text-red-500"
				>
					{{ searchStore.error }}
				</div>

				<!-- 搜索结果列表 -->
				<div v-else-if="searchStore.hasResults" class="animate-fade-in">
					<ul class="space-y-2">
						<li
							@click="clickResult(result)"
							v-for="result in searchStore.result"
							:key="result"
							class="p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer text-gray-800 dark:text-gray-200"
						>
							{{ result }}
						</li>
					</ul>
				</div>

				<!-- 无结果 -->
				<div v-else class="text-center pt-16 text-gray-500">
					<p>找不到与"{{ lastSearchedQuery }}"相关的结果</p>
					<p class="text-xs mt-1">请尝试其他关键词</p>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useSearchStore } from "@/store/modules/search";
import SearchInput from "@/components/SearchInput.vue";
import XIcon from "@/components/icon/XIcon.vue";
import SpinnerIcon from "@/components/icon/SpinnerIcon.vue";
import ToastModal from "@/modal/components/ToastModal.vue";
import { useModal } from "@/hooks/useModal";
import { useRouter } from "vue-router";

// 定义 emits 以便通知父组件关闭
const emit = defineEmits(["close"]);

const router = useRouter();

const modal = useModal();

const searchStore = useSearchStore();

// 本地 UI 状态
const searchQuery = ref("");
const isEditingHistory = ref(false);
const searchPerformed = ref(false); // 标记是否执行过搜索
const lastSearchedQuery = ref(""); // 存储上一次搜索的词，用于“无结果”提示

// 计算属性，用于控制显示哪个区域
const showHistorySection = computed(
	() => !searchPerformed.value && searchStore.hasHistory
);
const showResultsSection = computed(() => searchPerformed.value);

// 监听输入框变化，如果清空了，就返回历史记录视图
watch(searchQuery, newValue => {
	if (newValue.trim() === "") {
		searchPerformed.value = false;
		searchStore.clearResults();
	}
});

// 处理搜索事件
const handleSearch = () => {
	const query = searchQuery.value.trim();
	if (!query) return;

	lastSearchedQuery.value = query;
	searchPerformed.value = true;
	isEditingHistory.value = false; // 退出编辑模式
	searchStore.performSearch(query);
};

const clickResult = (value: string) => {
	router.push({
		name: "SearchPexels", // 对应你路由配置里的 name
		query: {
			q: value, // 'q' 是我们约定的查询参数名
		},
	});
};

// 点击历史记录进行搜索
const handleHistoryClick = (item: string) => {
	if (isEditingHistory.value) {
		modal.show(
			ToastModal,
			{ message: "请先退出编译模式" },
			{
				position: "center",
				animationType: "fade",
				showOverlay: false,
				closeOnClickOverlay: false,
				duration: 1000,
			}
		);
		return;
	}
	searchQuery.value = item;
	handleSearch();
};
</script>

<style scoped>
/* 添加一个简单的淡入动画 */
.animate-fade-in {
	animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(-10px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}
</style>
